package com.file.parser;

import com.file.bo.DomesticDiploma;
import com.file.bo.ResponseData;
import com.file.constant.ErrorCode;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;

@Slf4j
public class XlcxHtmlParser {

	public ResponseData<String> parseXlcxHtmlToJson(String daId, String filePath) {
		log.info("parseXlcxHtmlToJson started, daId:{}", daId);
		String json = null;

		try {
			File input = new File(filePath);
			Document doc = Jsoup.parse(input, "UTF-8");
			boolean isNewVersion = isNewVersion(doc);
			log.info("parseXlcxHtmlToJson, daId:{}, isNewVersion:{}", daId, isNewVersion);
			DomesticDiploma diploma = isNewVersion ? parseXlcxHtml_NewVersion(doc) : parseXlcxHtml(doc);
			json = JsonUtils.convertObjectToJson(diploma);
			doAlert(daId, diploma);
		} catch (Exception e) {
			log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseXlcxHtmlToJson failed", e);
			return new ResponseData<String>(json, ErrorCode.FILE_PARSE_EXCEPTION.getCode(),
					ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
		}

		log.info("parseXlcxHtmlToJson completed, daId:{}, json:{}", daId, json);
		return new ResponseData<String>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
	}

	//判断文件是否为新版文件
	private boolean isNewVersion(Document doc) {
		boolean isNewVersion = true;

		Element rowElement = doc.select(".card.rowcard").first();
		if (rowElement == null) {
			isNewVersion = false;
		}

		return isNewVersion;
	}


	//改版后的html解析
	public DomesticDiploma parseXlcxHtml_NewVersion(Document doc) throws IOException {
		DomesticDiploma domesticDiploma = new DomesticDiploma();

		Elements rowElements = doc.select(".collection > .row");

		for (Element element : rowElements) {
			switch (element.child(0).text()) {//NOSONAR
				case "姓名":
					String name = element.child(1).text();
					domesticDiploma.setName(name);
					break;
				case "性别":
					String sex = element.child(1).text();
					domesticDiploma.setSex(sex);
					break;
				case "出生日期":
					String dateOfBirth = element.child(1).text();
					domesticDiploma.setDateOfBirth(dateOfBirth);
					break;
				case "入学日期":
					String dateOfEnrollment = element.child(1).text();
					domesticDiploma.setDateOfEnrollment(dateOfEnrollment);
					break;
				case "毕（结）业日期":
					String dateOfGraduation = element.child(1).text();
					domesticDiploma.setDateOfGraduation(dateOfGraduation);
					break;
				case "学校名称":
					String schoolName = element.child(1).text();
					domesticDiploma.setSchoolName(schoolName);
					break;
				case "专业":
					String major = element.child(1).text();
					domesticDiploma.setMajor(major);
					break;
				case "学历类别":
					String diplomaClassification = element.child(1).text();
					domesticDiploma.setDiplomaClassification(diplomaClassification);
					break;
				case "学制":
					String schoolSystem = element.child(1).text();
					domesticDiploma.setSchoolSystem(schoolSystem);
					break;
				case "学习形式":
					String learningStyle = element.child(1).text();
					domesticDiploma.setLearningStyle(learningStyle);
					break;
				case "层次":
					String degree = element.child(1).text();
					domesticDiploma.setDegree(degree);
					break;
				case "毕（结）业":
					String graduation = element.child(1).text();
					domesticDiploma.setGraduation(graduation);
					break;
				case "校（院）长姓名":
					String principalName  = element.child(1).text();
					domesticDiploma.setPrincipalName(principalName);
					break;
				case "证书编号":
					String certificateNo  = element.child(1).text();
					domesticDiploma.setCertificateNo(certificateNo);
					break;
				case "证件号码":
					String idNo  = element.child(1).text();
					domesticDiploma.setIdNo(idNo);
					break;
				case "补证学校":
					String supplementaryCertificateSchool  = element.child(1).text();
					domesticDiploma.setSupplementaryCertificateSchool(supplementaryCertificateSchool);;
					break;
				case "补证日期":
					String supplementaryCertificateDate  = element.child(1).text();
					domesticDiploma.setSupplementaryCertificateDate(supplementaryCertificateDate);;
					break;
				case "补证编号":
					String supplementaryCertificateNo  = element.child(1).text();
					domesticDiploma.setSupplementaryCertificateNo(supplementaryCertificateNo);
					break;
			}
		}
		log.info(domesticDiploma.toString());

		return domesticDiploma;
	}

	public DomesticDiploma parseXlcxHtml(Document doc) throws IOException {
		DomesticDiploma domesticDiploma = new DomesticDiploma();
		
		Element span = doc.select("div.img-right > h6 > span").first();
		domesticDiploma.setSex(span.text());
		
		Element h6 = doc.select("div.img-right > h6").first();
		domesticDiploma.setName(h6.text().substring(0, h6.text().length()-1));
		
		Element p = doc.select("div.img-right > p").first();
		domesticDiploma.setDateOfBirth(p.text());
		
		Element div = doc.select("div.marginT20 > div").first();
		if (div.children().get(0).child(0).text().contains("姓名")) {
			div = doc.select("div.marginT20 > div").get(1);
		}
		
		Elements divChildren = div.children();
		for (Element element : divChildren) {
			switch (element.child(0).text()) {//NOSONAR
			case "入学日期":
				String dateOfEnrollment = element.child(1).text();
				domesticDiploma.setDateOfEnrollment(dateOfEnrollment);
				break;
			case "毕（结）业日期":
				String dateOfGraduation = element.child(1).text();
				domesticDiploma.setDateOfGraduation(dateOfGraduation);
				break;
			case "学校名称":
				String schoolName = element.child(1).text();
				domesticDiploma.setSchoolName(schoolName);
				break;
			case "专业":
				String major = element.child(1).text();
				domesticDiploma.setMajor(major);
				break;
			case "学历类别":
				String diplomaClassification = element.child(1).text();
				domesticDiploma.setDiplomaClassification(diplomaClassification);
				break;
			case "学制":
				String schoolSystem = element.child(1).text();
				domesticDiploma.setSchoolSystem(schoolSystem);
				break;
			case "学习形式":
				String learningStyle = element.child(1).text();
				domesticDiploma.setLearningStyle(learningStyle);
				break;
			case "层次":
				String degree = element.child(1).text();
				domesticDiploma.setDegree(degree);
				break;
			case "毕（结）业":
				String graduation = element.child(1).text();
				domesticDiploma.setGraduation(graduation);
				break;
			case "校（院）长姓名":
				String principalName  = element.child(1).text();
				domesticDiploma.setPrincipalName(principalName);
				break;
			case "证书编号":
				String certificateNo  = element.child(1).text();
				domesticDiploma.setCertificateNo(certificateNo);
				break;
			case "证件号码":
				String idNo  = element.child(1).text();
				domesticDiploma.setIdNo(idNo);
				break;
			case "补证学校":
				String supplementaryCertificateSchool  = element.child(1).text();
				domesticDiploma.setSupplementaryCertificateSchool(supplementaryCertificateSchool);;
				break;
			case "补证日期":
				String supplementaryCertificateDate  = element.child(1).text();
				domesticDiploma.setSupplementaryCertificateDate(supplementaryCertificateDate);;
				break;
			case "补证编号":
				String supplementaryCertificateNo  = element.child(1).text();
				domesticDiploma.setSupplementaryCertificateNo(supplementaryCertificateNo);
				break;
			}
		}
		log.info(domesticDiploma.toString());

		return domesticDiploma;

	}

	private void doAlert(String daId, DomesticDiploma domesticDiploma) {
		log.info("doAlert started daId: {}", daId);

		if (StringUtils.isBlank(domesticDiploma.getName())) {
			log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseXlcxHtmlToJson domesticDiploma Name is null");
			throw new RuntimeException();
		}

		if (StringUtils.isBlank(domesticDiploma.getDateOfGraduation())) {
			log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseXlcxHtmlToJson domesticDiploma DateOfGraduation is null");
			throw new RuntimeException();
		}

		if (StringUtils.isBlank(domesticDiploma.getDiplomaClassification())) {
			log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseXlcxHtmlToJson domesticDiploma DiplomaClassification is null");
			throw new RuntimeException();
		}

		if (StringUtils.isBlank(domesticDiploma.getDegree())) {
			log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseXlcxHtmlToJson domesticDiploma Degree is null");
			throw new RuntimeException();
		}

		if (StringUtils.isBlank(domesticDiploma.getSchoolName())) {
			log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseXlcxHtmlToJson domesticDiploma SchoolName is null");
			throw new RuntimeException();
		}

		if (StringUtils.isBlank(domesticDiploma.getMajor())) {
			log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseXlcxHtmlToJson domesticDiploma Major is null");
			throw new RuntimeException();
		}

		if (StringUtils.isBlank(domesticDiploma.getCertificateNo())) {
			log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseXlcxHtmlToJson domesticDiploma CertificateNo is null");
			throw new RuntimeException();
		}

		if (StringUtils.isBlank(domesticDiploma.getGraduation())) {
			log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseXlcxHtmlToJson domesticDiploma Graduation is null");
			throw new RuntimeException();
		}

		log.info("doAlert completed daId: {}", daId);
	}

	public static void main(String[] args) {
		// String filePath = "E:\\data\\file\\xlcx\\380842851853930262_a4a1654db9bf21bcd2ca440ce3b8a897_xlcx_xlzm.html";
		String filePath = "D:\\data\\file\\xlcx\\xlcx-0116.html";
		XlcxHtmlParser xlcxHtmlParser = new XlcxHtmlParser();
		String json = xlcxHtmlParser.parseXlcxHtmlToJson("", filePath).getData();
		System.out.println(json);

	}

}
